package com.xsp.proxy;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @author xsp
 * @date 2024/1/21
 * @desc
 */
@Component
@Aspect
public class BookServiceProxy {
    private Logger logger = LoggerFactory.getLogger(BookServiceProxy.class);

    @Pointcut(value = "execution(* com.xsp.service.BookInfoService.addBook(..))")
    public void pointcut() {

    }

    // 前置增强
//    @Before(value = "execution(* com.xsp.service.BookInfoService.addBook(..))")
    public void before(JoinPoint joinPoint) {
        logger.debug("执行前置增强，，，");
        logger.debug("准备执行" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
    }

    // 后置增强
//    @AfterReturning(value = "pointcut()", returning = "returnValue")
    public void afterReturning(JoinPoint joinPoint, Object returnValue) {
        logger.debug("执行后置增强，，，");
        // 后置增强是在目标方法结束后（没有异常发生的前提下）切入
        logger.debug("执行完" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
        logger.debug("方法执行的结果：{}", returnValue);
    }

    // 异常抛出增强
//    @AfterThrowing(value = "pointcut()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        logger.debug("执行异常抛出增强，，，");
        // 后置增强是在目标方法结束后（没有异常发生的前提下）切入
        logger.debug("执行" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
        logger.error("发生的异常：{}", e.getMessage());
    }

    // 最终增强
//    @After(value = "pointcut()")
    public void after(JoinPoint joinPoint) {
        logger.debug("执行最终增强，，，");
        // 后置增强是在目标方法结束后（没有异常发生的前提下）切入
        logger.debug("执行" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
    }

    // 环绕增强
    @Around(value = "pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) {
        logger.debug("执行环绕增强，，，");
        logger.debug("执行" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
        try {
            Object proceed = joinPoint.proceed();
            logger.debug("执行完" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
            logger.debug("方法执行的结果：{}", proceed);
            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
            logger.debug("执行" + joinPoint.getTarget() + "的方法:" + joinPoint.getSignature().getName());
            logger.error("发生的异常：{}", e.getMessage());
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }
}
